package com.example.system.class02;

/**
 * @Date 2022/7/18
 * @Created by Jonathan
 */
public class Code05_FirstMoreNumIndex {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 5, 7, 8, 9, 11};
        int[] arr1 = new int[]{1, 3, 5, 7, 9, 11};
        System.out.println(firstMoreThanNumIndex(arr, 2));
        System.out.println(firstMoreThanNumIndex(arr, 8));
        System.out.println(firstMoreThanNumIndex(arr1, 2));
        System.out.println(firstMoreThanNumIndex(arr1, 8));
    }

    // 1 3 5 7 9 10
    private static int firstMoreThanNumIndex(int[] arr, int num) {
        // -1 表示不存在
        if (arr == null || arr.length < 1 || arr[arr.length - 1] <= num) {
            return -1;
        }
        int L = 0;
        int R = arr.length - 1;
        int index = -1;
        while (L <= R) {
            int M = L + ((R - L) >> 1);
            // 是要找第一个比num大的索引下标
            // 在目前M位置已经比num大的情况下
            // 第一个数肯定是M位置或者M的左边
            if (arr[M] >= num) {
                index = M;
                R = M - 1;
            } else {
                L = M + 1;
            }
        }
        return index;
    }
}
